/**
 * Mock API处理器
 * 模拟API响应，替代真实的HTTP请求
 */

import {
  mockUserInfo,
  mockDepartments,
  mockRoles,
  mockEmployees,
  mockSystemConfig,
  mockLoginLogs,
  mockOperationLogs,
  mockNotices
} from './data.js'

/**
 * 模拟API响应延迟
 * @param {number} delay - 延迟时间（毫秒）
 */
const mockDelay = (delay = 300) => {
  return new Promise(resolve => setTimeout(resolve, delay))
}

/**
 * 创建成功响应
 * @param {any} data - 响应数据
 * @param {string} msg - 响应消息
 */
const createSuccessResponse = (data = null, msg = '操作成功') => {
  return {
    status: 1,
    msg,
    data
  }
}

/**
 * 创建失败响应
 * @param {string} msg - 错误消息
 */
const createErrorResponse = (msg = '操作失败') => {
  return {
    status: 0,
    msg,
    data: null
  }
}

/**
 * Mock API路由映射
 */
export const mockApiRoutes = {
  // 登录相关
  'api/index/login': async (data) => {
    await mockDelay()
    const { mobile, pwd } = data
    
    // 简单的登录验证
    if (mobile === '13800138000' && pwd === '123456') {
      return createSuccessResponse(mockUserInfo, '登录成功')
    } else {
      return createErrorResponse('用户名或密码错误')
    }
  },

  'api/index/sms': async (data) => {
    await mockDelay()
    return createSuccessResponse({ code: '123456' }, '验证码发送成功')
  },

  'api/Common/init': async () => {
    await mockDelay()
    return createSuccessResponse(mockUserInfo, '初始化成功')
  },

  'api/index/config': async () => {
    await mockDelay()
    return createSuccessResponse(mockSystemConfig, '获取配置成功')
  },

  // 部门管理
  'api/department/index': async () => {
    await mockDelay()
    return createSuccessResponse({ depart_list: mockDepartments }, '获取部门列表成功')
  },

  'api/department/add': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '新增部门成功')
  },

  'api/department/edit': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '修改部门成功')
  },

  'api/department/delete': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '删除部门成功')
  },

  // 员工管理
  'api/Employee/index': async (data) => {
    await mockDelay()
    // 根据部门ID筛选员工
    let filteredEmployees = mockEmployees
    if (data && data.did) {
      filteredEmployees = mockEmployees.filter(emp => emp.department_id === data.did)
    }

    return createSuccessResponse({
      list: filteredEmployees,
      count: filteredEmployees.length
    }, '获取员工列表成功')
  },

  'api/Employee/add': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '新增员工成功')
  },

  'api/Employee/edit': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '修改员工成功')
  },

  'api/Employee/delete': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '删除员工成功')
  },

  // 获取部门下的员工列表（用于选择负责人）
  'api/Common/get_sub_department_employee': async (data) => {
    await mockDelay()
    // 根据部门ID筛选员工，并添加"空缺"选项
    let filteredEmployees = []
    if (data && data.did) {
      filteredEmployees = mockEmployees.filter(emp => emp.department_id === data.did)
    }

    // 在开头添加"空缺"选项
    const employeeOptions = [
      { id: '', name: '空缺' },
      ...filteredEmployees.map(emp => ({ id: emp.id, name: emp.name }))
    ]

    return createSuccessResponse(employeeOptions, '获取员工选项成功')
  },

  // 角色管理
  'api/role/index': async () => {
    await mockDelay()
    return createSuccessResponse({ list: mockRoles }, '获取角色列表成功')
  },

  'api/role/add': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '新增角色成功')
  },

  'api/role/edit': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '修改角色成功')
  },

  'api/role/delete': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '删除角色成功')
  },

  'api/role/get_func': async (data) => {
    await mockDelay()
    return createSuccessResponse(mockUserInfo.func_list, '获取角色权限成功')
  },

  'api/role/set_func': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '设置角色权限成功')
  },

  // 菜单管理
  'api/menu/index': async () => {
    await mockDelay()
    return createSuccessResponse({ menu_list: mockUserInfo.menu_list }, '获取菜单列表成功')
  },

  'api/menu/add': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '新增菜单成功')
  },

  'api/menu/edit': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '修改菜单成功')
  },

  'api/menu/delete': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '删除菜单成功')
  },

  // 功能管理
  'api/func/index': async (data) => {
    await mockDelay()
    return createSuccessResponse({ list: mockUserInfo.func_list }, '获取功能列表成功')
  },

  'api/func/add': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '新增功能成功')
  },

  'api/func/edit': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '修改功能成功')
  },

  'api/func/delete': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '删除功能成功')
  },

  // 系统设置
  'api/config/index': async () => {
    await mockDelay()
    return createSuccessResponse({
      config: mockSystemConfig,
      sms: [
        { account: 'test_account', password: 'test_password', apikey: 'test_apikey' }
      ]
    }, '获取系统设置成功')
  },

  'api/config/edit': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '保存系统设置成功')
  },

  // 系统公告
  'api/Notice/index': async (data) => {
    await mockDelay()
    return createSuccessResponse({
      list: mockNotices,
      count: mockNotices.length
    }, '获取系统公告成功')
  },

  'api/Notice/add': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '新增公告成功')
  },

  'api/Notice/edit': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '修改公告成功')
  },

  'api/Notice/delete': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '删除公告成功')
  },

  // 日志管理
  'api/employeeLoginLog/index': async (data) => {
    await mockDelay()
    return createSuccessResponse({
      list: mockLoginLogs,
      count: mockLoginLogs.length
    }, '获取登录日志成功')
  },

  'api/employeeOperationLog/index': async (data) => {
    await mockDelay()
    return createSuccessResponse({
      list: mockOperationLogs,
      count: mockOperationLogs.length
    }, '获取操作日志成功')
  },

  // 来访登记
  'api/index/visit': async (data) => {
    await mockDelay()
    return createSuccessResponse(null, '来访登记成功')
  },

  // 通用接口
  'api/common/upload': async (data) => {
    await mockDelay()
    return createSuccessResponse({
      url: '/mock/upload/file.jpg',
      filename: 'file.jpg'
    }, '文件上传成功')
  }
}

/**
 * 处理Mock API请求
 * @param {string} url - 请求URL
 * @param {Object} data - 请求数据
 * @returns {Promise} Mock响应
 */
export const handleMockRequest = async (url, data = {}) => {
  // 清理URL，移除开头的斜杠和查询参数
  const cleanUrl = url.replace(/^\/+/, '').split('?')[0]
  
  // 查找对应的Mock处理器
  const handler = mockApiRoutes[cleanUrl]
  
  if (handler) {
    try {
      return await handler(data)
    } catch (error) {
      console.error(`Mock API处理错误 [${cleanUrl}]:`, error)
      return createErrorResponse('Mock API处理错误')
    }
  } else {
    console.warn(`未找到Mock API处理器: ${cleanUrl}`)
    return createErrorResponse(`接口不存在: ${cleanUrl}`)
  }
}
